<template>
  <div class="container">
    <h2>辅食记录管理</h2>
    
    <!-- 添加记录按钮 -->
    <div class="add-button-container">
      <button @click="showForm = true" class="add-btn">添加辅食记录</button>
    </div>

    <!-- 添加/编辑表单 -->
    <div v-if="showForm" class="form-overlay">
      <div class="form-container">
        <h3>{{ newRecord.id ? '编辑' : '添加' }}辅食记录</h3>
        <form @submit.prevent="submitRecord">
          <div class="form-group">
            <h4>喂食日期</h4>
            <input type="date" v-model="newRecord.date" required class="date-input">
          </div>
          <div class="form-group">
            <h4>喂食时间</h4>
            <input type="time" v-model="newRecord.time" required class="time-input">
          </div>
          
          <!-- 食物选择区域 -->
          <div class="form-group">
            <h4>辅食内容</h4>
            <div class="food-selection">
              <!-- 类别选择 -->
              <div class="category-tabs">
                <button 
                  v-for="category in foodCategories" 
                  :key="category.id"
                  type="button"
                  @click="selectedCategory = category.id"
                  :class="['category-tab', { active: selectedCategory === category.id }]"
                >
                  {{ category.name }}
                </button>
              </div>
              
              <!-- 食物选项 -->
              <div class="food-options">
                <div 
                  v-for="option in filteredFoodOptions" 
                  :key="option.id"
                  class="food-option"
                >
                  <label class="food-checkbox">
                    <input 
                      type="checkbox" 
                      :value="option.id"
                      v-model="selectedFoods"
                    >
                    <span>{{ option.name }}</span>
                    <!-- <span v-if="option.is_custom" class="custom-tag">自定义</span> -->
                  </label>
                  <button 
                    v-if="option.is_custom" 
                    @click="deleteFoodOption(option.id, option.name)"
                    class="delete-food-btn"
                    type="button"
                    title="删除自定义食物"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </button>
                </div>
              </div>
              
              <!-- 自定义食物添加 -->
              <div class="custom-food-section">
                <h5>添加自定义食物</h5>
                <div class="custom-food-form">
                  <select v-model="customFood.category_id" class="custom-category-select">
                    <option value="">选择类别</option>
                    <option v-for="category in foodCategories" :key="category.id" :value="category.id">
                      {{ category.name }}
                    </option>
                  </select>
                  <input 
                    v-model="customFood.name" 
                    placeholder="输入食物名称" 
                    class="custom-food-input"
                  >
                  <button 
                    type="button" 
                    @click="addCustomFood"
                    :disabled="!customFood.name || !customFood.category_id"
                    class="add-custom-btn"
                  >
                    添加
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 接受程度选择 -->
          <div class="form-group">
            <h4>接受程度</h4>
            <select 
              v-model="newRecord.acceptance_level" 
              required
              class="acceptance-select"
            >
              <option value="">选择接受程度</option>
              <option value="喜欢">😊 喜欢</option>
              <option value="一般">😐 一般</option>
              <option value="不喜欢">😞 不喜欢</option>
              <option value="过敏">⚠️ 过敏</option>
            </select>
          </div>
          
          <div class="form-group">
            <h4>备注</h4>
            <textarea 
              v-model="newRecord.notes" 
              placeholder="记录宝宝的反应、食量等..."
              class="notes-input"
              rows="3"
            ></textarea>
          </div>
          
          <div class="button-group">
            <button type="button" @click="cancelForm">取消</button>
            <button type="submit" :disabled="isSubmitting || selectedFoods.length === 0">
              {{ isSubmitting ? '提交中...' : '提交' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-controls">
      <select v-model="itemsPerPage" @change="currentPage = 1">
        <option v-for="option in pageSizeOptions" :value="option" :key="option">
          每页 {{ option }} 条
        </option>
      </select>
      
      <div class="pagination">
        <button @click="currentPage = Math.max(1, currentPage - 1)" :disabled="currentPage === 1">
          上一页
        </button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button @click="currentPage = currentPage + 1" :disabled="currentPage >= totalPages">
          下一页
        </button>
      </div>
    </div>

    <!-- 记录列表 -->
    <div class="record-list">
      <template v-for="(record, index) in paginatedRecords" :key="record.id">
        <div v-if="shouldShowDateDivider(record, index)" class="date-divider">
          {{ formatDate(record.date) }}
        </div>
        <div class="record-item">
          <div class="record-header">
            <div class="record-time">{{ record.time }}</div>
            <div class="record-acceptance">
              <span :class="['acceptance-badge', getAcceptanceClass(record.acceptance_level)]">
                {{ getAcceptanceEmoji(record.acceptance_level) }} {{ record.acceptance_level }}
              </span>
            </div>
            <div class="record-actions">
              <button @click="editRecord(record)" class="edit-btn">编辑</button>
              <button @click="deleteRecord(record.id)" class="delete-btn">删除</button>
            </div>
          </div>
          <div class="record-content">
            <div class="food-details">
              <div 
                v-for="detail in record.details" 
                :key="detail.id"
                class="food-detail-item"
              >
                <span class="food-name">{{ detail.food_name }}</span>
                <span class="food-category">[{{ detail.food_category }}]</span>
              </div>
            </div>
            <div v-if="record.notes" class="record-notes">
              <strong>备注：</strong>{{ record.notes }}
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'

// 响应式数据
const records = ref([])
const foodCategories = ref([])
const foodOptions = ref([])
const showForm = ref(false)
const isSubmitting = ref(false)
const selectedCategory = ref(null)
const selectedFoods = ref([])
const currentPage = ref(1)
const itemsPerPage = ref(50)
const pageSizeOptions = [10, 50, 100]

// 表单数据
const newRecord = ref({
  id: null,
  date: dayjs().format('YYYY-MM-DD'),
  time: dayjs().format('HH:mm'),
  acceptance_level: '',
  notes: ''
})

// 自定义食物
const customFood = ref({
  name: '',
  category_id: null
})

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(records.value.length / itemsPerPage.value)
})

const paginatedRecords = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage.value
  const endIndex = startIndex + itemsPerPage.value
  return records.value.slice(startIndex, endIndex)
})

const filteredFoodOptions = computed(() => {
  if (!selectedCategory.value) return []
  return foodOptions.value.filter(option => option.category_id === selectedCategory.value)
})

// 生命周期
onMounted(async () => {
  await loadData()
})

// 方法
async function loadData() {
  try {
    await Promise.all([
      loadRecords(),
      loadFoodCategories(),
      loadFoodOptions()
    ])
    
    // 默认选择第一个类别
    if (foodCategories.value.length > 0) {
      selectedCategory.value = foodCategories.value[0].id
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    alert('加载数据失败')
  }
}

async function loadRecords() {
  const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/complementary-food-records`)
  records.value = response.data
}

async function loadFoodCategories() {
  const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/food-categories`)
  foodCategories.value = response.data
}

async function loadFoodOptions() {
  const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/food-options`)
  foodOptions.value = response.data
}



async function addCustomFood() {
  if (!customFood.value.name || !customFood.value.category_id) {
    alert('请填写完整的自定义食物信息')
    return
  }
  
  try {
    const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/food-options`, {
      name: customFood.value.name,
      category_id: customFood.value.category_id,
      is_custom: true
    })
    
    // 添加到本地列表
    foodOptions.value.push(response.data)
    
    // 清空表单
    customFood.value = { name: '', category_id: null }
    
    alert('自定义食物添加成功')
  } catch (error) {
    console.error('添加自定义食物失败:', error)
    alert('添加自定义食物失败')
  }
}

async function submitRecord() {
  if (isSubmitting.value) {
    alert('正在提交中，请勿重复点击')
    return
  }
  
  if (selectedFoods.value.length === 0) {
    alert('请至少选择一种食物')
    return
  }
  
  if (!newRecord.value.acceptance_level) {
    alert('请选择接受程度')
    return
  }
  
  isSubmitting.value = true
  
  try {
    const details = selectedFoods.value.map(foodId => ({
      food_option_id: foodId
    }))
    
    const payload = {
      date: newRecord.value.date,
      time: newRecord.value.time,
      acceptance_level: newRecord.value.acceptance_level,
      notes: newRecord.value.notes,
      details: details
    }
    
    if (newRecord.value.id) {
      await axios.put(`${import.meta.env.VITE_API_BASE_URL}/api/complementary-food-records/${newRecord.value.id}`, payload)
      alert('修改成功')
    } else {
      await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/complementary-food-records`, payload)
      alert('添加成功')
    }
    
    await loadRecords()
    cancelForm()
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

function editRecord(record) {
  newRecord.value = {
    id: record.id,
    date: record.date,
    time: record.time,
    acceptance_level: record.acceptance_level,
    notes: record.notes
  }
  
  // 设置选中的食物
  selectedFoods.value = record.details.map(detail => detail.food_option_id || 
    foodOptions.value.find(opt => opt.name === detail.food_name)?.id).filter(Boolean)
  
  showForm.value = true
}

async function deleteRecord(id) {
  if (!confirm('确定要删除这条记录吗？')) return
  
  try {
    await axios.delete(`${import.meta.env.VITE_API_BASE_URL}/api/complementary-food-records/${id}`)
    await loadRecords()
    alert('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败')
  }
}

async function deleteFoodOption(foodId, foodName) {
  if (!confirm(`确定要删除自定义食物"${foodName}"吗？\n删除后将无法恢复。`)) return
  
  try {
    await axios.delete(`${import.meta.env.VITE_API_BASE_URL}/api/food-options/${foodId}`)
    
    // 重新加载食物选项
    await loadFoodOptions()
    
    // 如果当前选中的食物中包含被删除的食物，需要从选中列表中移除
    selectedFoods.value = selectedFoods.value.filter(id => id !== foodId)
    
    alert('删除成功')
  } catch (error) {
    console.error('删除食物选项失败:', error)
    
    // 处理后端返回的错误信息
    if (error.response && error.response.data && error.response.data.error) {
      alert(error.response.data.error)
    } else {
      alert('删除失败，请重试')
    }
  }
}

function cancelForm() {
  showForm.value = false
  newRecord.value = {
    id: null,
    date: dayjs().format('YYYY-MM-DD'),
    time: dayjs().format('HH:mm'),
    acceptance_level: '',
    notes: ''
  }
  selectedFoods.value = []
  customFood.value = { name: '', category_id: null }
}

function shouldShowDateDivider(record, index) {
  const recordIndex = records.value.findIndex(r => r.id === record.id)
  return recordIndex === 0 || !isSameDate(record.date, records.value[recordIndex - 1].date)
}

function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD')
}

function isSameDate(date1, date2) {
  return dayjs(date1).isSame(dayjs(date2), 'day')
}

function getAcceptanceClass(level) {
  const classMap = {
    '喜欢': 'like',
    '一般': 'neutral',
    '不喜欢': 'dislike',
    '过敏': 'allergy'
  }
  return classMap[level] || 'neutral'
}

function getAcceptanceEmoji(level) {
  const emojiMap = {
    '喜欢': '😊',
    '一般': '😐',
    '不喜欢': '😞',
    '过敏': '⚠️'
  }
  return emojiMap[level] || '😐'
}
</script>

<style scoped>
.container {
  padding: 15px;
  margin-top: 10px;
  max-width: 100%;
  overflow-x: hidden;
}

h2 {
  font-size: 36px;
  margin-bottom: 25px;
  text-align: center;
  color: #2c3e50;
}

.add-button-container {
  margin-bottom: 20px;
  text-align: center;
}

.add-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 15px 30px;
  border-radius: 8px;
  font-size: 20px;
  font-weight: bold;
  cursor: pointer;
}

.add-btn:hover {
  background-color: #45a049;
}

/* 表单样式 */
.form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.form-container {
  background: white;
  border-radius: 10px;
  padding: 20px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 20px;
}

.form-group h4 {
  margin-bottom: 8px;
  font-size: 18px;
  color: #333;
}

.date-input, .time-input, .notes-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 18px;
  box-sizing: border-box;
}

.notes-input {
  resize: vertical;
  min-height: 80px;
}

/* 食物选择样式 */
.food-selection {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
}

.category-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.category-tab {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background: white;
  color: #666;
  font-size: 14px;
  cursor: pointer;
}

.category-tab.active {
  background: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.food-options {
  margin-bottom: 20px;
}

.food-option {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  cursor: pointer;
  flex: 1;
}

.delete-food-btn {
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  min-width: 24px;
  min-height: 24px;
  max-width: 24px;
  max-height: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 8px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 6px rgba(255, 71, 87, 0.3);
  opacity: 0.9;
  flex-shrink: 0;
  padding: 0;
}

.delete-food-btn:hover {
  background: #ff3742;
  transform: scale(1.1);
  box-shadow: 0 3px 8px rgba(255, 71, 87, 0.4);
  opacity: 1;
}

.delete-food-btn:active {
  transform: scale(1.05);
  box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
}

.delete-food-btn svg {
  display: block;
  pointer-events: none;
}

.custom-tag {
  background: #ff9800;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.acceptance-level {
  margin-top: 10px;
  margin-left: 24px;
}

.acceptance-select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

/* 自定义食物样式 */
.custom-food-section {
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.custom-food-section h5 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #666;
}

.custom-food-form {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.custom-category-select, .custom-food-input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.custom-food-input {
  flex: 1;
  min-width: 120px;
}

.add-custom-btn {
  padding: 8px 16px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.add-custom-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.button-group {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 20px;
}

.button-group button {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

.button-group button[type="button"] {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.button-group button[type="submit"] {
  background-color: #4CAF50;
  color: white;
}

.button-group button[type="submit"]:disabled {
  background-color: #cccccc;
  color: #666666;
  cursor: not-allowed;
  opacity: 0.6;
}

/* 记录列表样式 */
.record-list {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.date-divider {
  padding: 12px 15px;
  font-weight: bold;
  font-size: 18px;
  color: #333;
  background-color: #f0f8f0;
  border-left: 4px solid #4CAF50;
}

.record-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.record-time {
  font-size: 18px;
  font-weight: bold;
  color: #666;
}

.record-acceptance {
  display: flex;
  align-items: center;
}

.record-actions {
  display: flex;
  gap: 8px;
}

.edit-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.edit-btn {
  background: #2196F3;
  color: white;
}

.delete-btn {
  background: #ff4444;
  color: white;
}

.record-content {
  margin-top: 10px;
}

.food-details {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.food-detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 10px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
}

.food-name {
  font-weight: bold;
}

.food-category {
  color: #666;
  font-size: 12px;
}

.acceptance-badge {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.acceptance-badge.like {
  background: #d4edda;
  color: #155724;
}

.acceptance-badge.neutral {
  background: #fff3cd;
  color: #856404;
}

.acceptance-badge.dislike {
  background: #f8d7da;
  color: #721c24;
}

.acceptance-badge.allergy {
  background: #f5c6cb;
  color: #721c24;
}

.record-notes {
  font-size: 14px;
  color: #666;
  font-style: italic;
}

/* 分页样式 */
.pagination-controls {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-controls select {
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 16px;
  background-color: white;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-radius: 8px;
  padding: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.pagination button {
  padding: 12px 15px;
  border: none;
  border-radius: 6px;
  background: #f5f5f5;
  color: #333;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: #999;
}

.pagination span {
  font-size: 16px;
  color: #666;
}
</style>